package com.hmdp.service.impl;

import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisConstants;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result getTypeList() {
        String typeKey = RedisConstants.CACHE_TYPE_KEY;
        try {
            // 从Redis查询
            List<String> typeJsonList = stringRedisTemplate.opsForList().range(typeKey, 0, -1);
            if (typeJsonList != null && !typeJsonList.isEmpty()) {
                // 转换并返回
                List<ShopType> typeList = new ArrayList<>();
                for (String json : typeJsonList) {
                    typeList.add(JSONUtil.toBean(json, ShopType.class));
                }
                return Result.ok(typeList);
            }
        } catch (Exception e) {
            // 记录日志，Redis异常时不影响后续流程
            log.error("Redis操作异常", e);
        }

        // Redis无数据或异常，查询数据库
        List<ShopType> typeList = query().orderByAsc("sort").list();
        // 写入Redis（同样可以加try-catch，避免缓存失败影响主流程）
        try {
            List<String> jsonList = typeList.stream()
                    .map(JSONUtil::toJsonStr)
                    .collect(Collectors.toList());
            stringRedisTemplate.opsForList().rightPushAll(typeKey, jsonList);
            stringRedisTemplate.expire(typeKey, RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
        } catch (Exception e) {
            log.error("Redis写入异常", e);
        }
        return Result.ok(typeList);
    }
}
